# -*- coding: utf-8 -*-
from PyQt5.QtSerialPort import QSerialPort
from PyQt5.QtCore import pyqtSignal, QObject

class SerialWork(QObject):
  signalReceive = pyqtSignal(object)

  def __init__(self, _port="/dev/ttySAC2", _baudrate=115200):
    super().__init__()
    self.port = _port
    self.baudrate = _baudrate

    self.com = QSerialPort(
            _port,
            baudRate=_baudrate,
            readyRead=self.ReadData
    )

    self.com.setDataBits(8)
    self.com.setParity(QSerialPort.NoParity)
    self.com.setStopBits(QSerialPort.OneStop)

  def open(self):
    if self.com.open(QSerialPort.ReadWrite) == False:
      print(self.port +": Open port error!")
      print(self.com.errorString())
      return

  def isOpen(self):
    return self.com.isOpen()

  def ReadData(self):
    revData = self.com.readAll()
    data = bytes(revData)

    if len(revData) > 0:
      self.signalReceive.emit(data)

  def sendData(self, outData):
    #print(self.port, "writes: ", outData.hex(" "))
    try:
      self.com.write(outData)
    except:
      print(self.port, ": something wrong when sending! ")


  def setRcvCallBack(self, function):
    self.signalReceive.connect(function)